package com.fulin.leetcode;

/**
 * @Description 正则表达式 * 和 . 的逻辑实现
 * @Author fulin16
 * @Date 2020/10/23 17:35
 **/
public class Num10_正则匹配 {
    private static State state = State.Init;
    private static char sChar;
    private static char pChar;

    private static int pos = 0;

    public static void main(String[] args) {
        String s = "abd";
        String p = ".*d";
        System.out.println(isMatch(s,p));
    }

    private static State initState(String p){
        if(pos == p.length()){
            return State.Eed;
        }
        pChar = p.charAt(pos++);
        if('.' == pChar){
            return State.Dot;
        }else if('*' == pChar){
            while('*' == pChar){
                if(pos == p.length()){
                    return State.Star3;
                }
                pChar = p.charAt(pos++);
            }
            return State.Star2;
        }else{
            return State.Other;
        }
    }

    public static boolean isMatch(String s, String p) {
        state = initState(p);
        for(int i = 0 ; i < s.length();i ++){
            sChar = s.charAt(i);
            switch (state) {
                case Init:
                    //如果状态机是初始状态则尝试更新状态
                    state = initState(p);
                    break;
                case Dot:
                    //状态机处于Dot状态
                    state = initState(p);
                    break;
                case Star2:
                    //状态机处于Star2状态
//                    if(pChar == sChar){
//                        state = initState(p);
//                    }
//                    if(i == s.length() - 1){
//                        return false;
//                    }

                    break;
                case Star3:
                    return true;
                case Other:
                    if(pChar != sChar){
                        return false;
                    }else{
                        state = initState(p);
                        break;
                    }
                case Eed:
                    return false;
                default:
                    break;
            }
        }
        return true;
    }


    /**
     * 有限状态机的状态
     */
    private static enum State{
        Init,   //开始
        Dot,    //点
        Star,   //*
        Star2,  //*后
        Star3, //*完
        Other,  //其他
        Eed;    //结束
    }
}
